﻿//==============================================================================
// File: PerTypePropertyScope.cs
// Created: 2010-05-10
// Author: Piotr Włodek
//==============================================================================
// This file is a part of MAMMOTH project.
// Copyright (C) 2010 AGH University of Science and Technology, Krakow.
// https://caribou.iisg.agh.edu.pl/trac/mammoth
//
// Mammoth is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// Mammoth is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public License
// along with WpfRcp. If not, see http://www.gnu.org/licenses/.
//==============================================================================

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using WpfRcp.PropertyModel.Core;
using Res = WpfRcp.PropertyModel.Properties.Resources;

namespace WpfRcp.PropertyModel.Scope
{
    /// <summary>
    /// Defines a property scope that can register dynamic properties per instance of the scope
    /// as well as per scope instance per type.
    /// </summary>
    [Serializable]
    public class PerTypePropertyScope : PropertyScope, IPerTypeDynamicPropertyRegistry
    {
        private readonly IDictionary<Type, MetaPropertyCollection> m_MetaPropertyCollectionMap;
        private readonly List<Type> m_SupportedTypes;

        /// <summary>
        /// Initializes a new instance of the <see cref="PerTypePropertyScope"/> class.
        /// </summary>
        /// <param name="supportedTypes">Collection of types supported by the scope.</param>
        /// <remarks>
        /// If <paramref name="supportedTypes"/> collection is not empty, it will be possible
        /// to register dynamic properties per supported type. Registering dynamic property
        /// per unsupported type will result in an exception being thrown.
        /// </remarks>
        public PerTypePropertyScope(IEnumerable<Type> supportedTypes)
            : this(supportedTypes.ToArray())
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="PerTypePropertyScope"/> class.
        /// </summary>
        /// <param name="supportedTypes">Collection of types supported by the scope.</param>
        /// <remarks>
        /// If <paramref name="supportedTypes"/> collection is not empty, it will be possible
        /// to register dynamic properties per supported type. Registering dynamic property
        /// per unsupported type will result in an exception being thrown.
        /// </remarks>
        public PerTypePropertyScope(params Type[] supportedTypes)
        {
            m_MetaPropertyCollectionMap = new Dictionary<Type, MetaPropertyCollection>();
            m_SupportedTypes = new List<Type>(supportedTypes);
        }

        #region IPerTypeDynamicPropertyRegistry Implementation

        /// <summary>
        /// Registers dynamic property per type, per dataset instance. 
        /// Enables adding custom properties to types only in context of single 
        /// dataset instance, not affecting other dataset instances.
        /// </summary>
        /// <param name="name">Property name.</param>
        /// <param name="propertyType">Property CLR type.</param>
        /// <param name="owner">Owning type, which belongs to this dataset.</param>
        /// <returns>Newly created <see cref="MetaProperty"/> instance.</returns>
        public MetaProperty RegisterDynamic(string name, Type propertyType, Type owner)
        {
            if (Disposed)
                throw new ObjectDisposedException(Res.ExceptionObjectAlreadyDisposed);

            return RegisterDynamic(name, propertyType, owner, new PropertyMetadata());
        }

        /// <summary>
        /// Registers dynamic property per type, per dataset instance. 
        /// Enables adding custom properties to types only in context of single 
        /// dataset instance, not affecting other dataset instances.
        /// </summary>
        /// <param name="name">Property name.</param>
        /// <param name="propertyType">Property CLR type.</param>
        /// <param name="owner">Owning type, which belongs to this dataset.</param>
        /// <param name="metadata">Property metadata.</param>
        /// <returns>Newly created <see cref="MetaProperty"/> instance.</returns>
        public MetaProperty RegisterDynamic(string name, Type propertyType, Type owner, PropertyMetadata metadata)
        {
            if (Disposed)
                throw new ObjectDisposedException(Res.ExceptionObjectAlreadyDisposed);

            if (IsSealed)
                throw new PropertyScopeException(Res.ExceptionPropertyScopeSealed);

            if (string.IsNullOrEmpty(name))
                throw new MetaPropertyException(Res.ExceptionPropertyNameNull);

            if (m_SupportedTypes.Count > 0 && !m_SupportedTypes.Contains(owner))
                throw new MetaPropertyException(string.Format(Res.ExceptionProvidedTypeNotSupported, owner.Name));

            MetaPropertyCollection collection = GetPropertyListCache(owner);
            Debug.Assert(collection != null);

            if (collection.Contains(name))
                throw new PropertyScopeException(string.Format(Res.ExceptionNameAlreadyExists, name));

            var metaProperty = PropertyManager.RegisterDynamicScoped(name, propertyType, GetType(), metadata);
            collection.Add(metaProperty);

            OnScopeChanged(metaProperty, null, owner);

            return metaProperty;
        }

        /// <summary>
        /// Unregisters dynamic property from type, from dataset instance.
        /// </summary>
        /// <param name="metaProperty"><see cref="MetaProperty"/> instace.</param>
        /// <param name="owner">Owning type, which belongs to this dataset.</param>
        public void UnregisterDynamic(MetaProperty metaProperty, Type owner)
        {
            if (Disposed)
                throw new ObjectDisposedException(Res.ExceptionObjectAlreadyDisposed);

            if (IsSealed)
                throw new PropertyScopeException(Res.ExceptionPropertyScopeSealed);

            MetaPropertyCollection collection = GetPropertyListCache(owner);
            Debug.Assert(collection != null);

            bool removed = collection.Remove(metaProperty);
            Debug.Assert(removed);

            OnScopeChanged(null, metaProperty, owner);
        }

        /// <summary>
        /// Unregisters dynamic property from type, from dataset instance.
        /// </summary>
        /// <param name="propertyName">Property name.</param>
        /// <param name="owner">Owning type, which belongs to this dataset.</param>
        public void UnregisterDynamic(string propertyName, Type owner)
        {
            if (Disposed)
                throw new ObjectDisposedException(Res.ExceptionObjectAlreadyDisposed);

            if (IsSealed)
                throw new PropertyScopeException(Res.ExceptionPropertyScopeSealed);

            MetaPropertyCollection collection = GetPropertyListCache(owner);
            Debug.Assert(collection != null);

            var metaProperty = (from prop in collection
                                where prop.Name == propertyName
                                select prop).FirstOrDefault();

            bool removed = collection.Remove(metaProperty);
            Debug.Assert(removed);

            OnScopeChanged(null, metaProperty, owner);
        }

        /// <summary>
        /// Returns a collection of meta properties that apply for the specified type.
        /// </summary>
        /// <param name="owner">Type for which meta properties are being retreived.</param>
        /// <returns>Returns a collection of meta properties that apply for the specified type.
        /// If null is provided, a collection of meta properties registered for any
        /// type is returned. For a non-null type, an empty collection is returned.</returns>
        public MetaPropertyCollection GetDynamicProperties(Type owner)
        {
            return GetDynamicProperties(owner, true);
        }

        /// <summary>
        /// Returns a collection of meta properties that apply for the specified type. Does not include
        /// properties registered per scope.
        /// </summary>
        /// <param name="owner">Type for which meta properties are being retreived.</param>
        /// <param name="includeTypeHierarchy">If true, type hierarchy is included. If false,
        /// a collection of meta properties that apply only for the specified type is returned.
        /// </param>
        /// <returns>Returns a collection of meta properties that apply for the specified type.
        /// If null is provided, a collection of meta properties registered for any
        /// type is returned.</returns>
        public MetaPropertyCollection GetDynamicProperties(Type owner, bool includeTypeHierarchy)
        {
            if (owner == null)
                return base.GetDynamicProperties(null);

            var metaPropertyCollection = new MetaPropertyCollection();

            // Find properties declared for interfaces
            if (includeTypeHierarchy)
            {
                foreach (var implementedInterfaces in owner.GetInterfaces())
                {
                    var metaProperties = GetPropertyEnumeration(implementedInterfaces);
                    metaPropertyCollection.AddRange(metaProperties);
                }
            }

            // Find properties declared for class and superclasses
            do
            {
                var metaProperties = GetPropertyEnumeration(owner);
                metaPropertyCollection.AddRange(metaProperties);
                owner = owner.BaseType;
            } 
            while (includeTypeHierarchy && owner != null && owner != typeof(object));

            return metaPropertyCollection;
        }

        /// <summary>
        /// Gets types supported by this dynamic property registry.
        /// </summary>
        public IEnumerable<Type> SupportedTypes
        {
            get { return m_SupportedTypes; }
        }

        #endregion

        #region Public Members

        /// <summary>
        /// Method that returns all dynamic properties registered in the registry.
        /// </summary>
        /// <param name="container">The container for which <see cref="MetaPropertyCollection"/> is being returned.</param>
        /// <returns>Returns all dynamic properties registered in the registry for given <see cref="IPropertyContainer"/> container.</returns>
        /// <remarks>The <paramref name="container"/> parameter can be null.</remarks>
        public override MetaPropertyCollection GetDynamicProperties(IPropertyContainer container)
        {
            if (container == null)
                return base.GetDynamicProperties(null);

            var collection = new MetaPropertyCollection();
            collection.AddRange(base.GetDynamicProperties(null));
            collection.AddRange(GetDynamicProperties(container.PropertyContainerType.SystemType));

            return collection;
        }

        /// <summary>
        /// Gets a value indicating whether it is possible to modify supported types collection.
        /// </summary>
        public bool AreSupportedTypesSealed { get; private set; }

        /// <summary>
        /// Makes supported types collection sealed.
        /// </summary>
        public void SealSupportedTypes()
        {
            AreSupportedTypesSealed = true;
        }

        /// <summary>
        /// Adds new supported type.
        /// </summary>
        /// <param name="type">Supported type to be added.</param>
        public void AddSupportedType(Type type)
        {
            if (Disposed)
                throw new ObjectDisposedException(Res.ExceptionObjectAlreadyDisposed);

            if (IsSealed)
                throw new PropertyScopeException(Res.ExceptionPropertyScopeSealed);

            if (AreSupportedTypesSealed)
                throw new PropertyScopeException(Res.ExceptionSupportedTypesSealed);
            
            m_SupportedTypes.Add(type);
        }

        /// <summary>
        /// Removes given supported type.
        /// </summary>
        /// <param name="type">Supported type to be removed.</param>
        public bool RemoveSupportedType(Type type)
        {
            if (Disposed)
                throw new ObjectDisposedException(Res.ExceptionObjectAlreadyDisposed);

            if (IsSealed)
                throw new PropertyScopeException(Res.ExceptionPropertyScopeSealed);

            if (AreSupportedTypesSealed)
                throw new PropertyScopeException(Res.ExceptionSupportedTypesSealed);

            return m_SupportedTypes.Remove(type);
        }

        #endregion

        #region Cleanup Implementation

        protected override void Dispose(bool disposing)
        {
            try
            {
                m_MetaPropertyCollectionMap.Clear();
            }
            finally
            {
                base.Dispose(disposing);
            }
        }

        #endregion

        #region Private Implementation

        private MetaPropertyCollection GetPropertyListCache(Type objectType)
        {
            MetaPropertyCollection list;

            if (!(m_MetaPropertyCollectionMap.TryGetValue(objectType, out list)))
            {
                lock (m_MetaPropertyCollectionMap)
                {
                    if (!(m_MetaPropertyCollectionMap.TryGetValue(objectType, out list)))
                    {
                        list = new MetaPropertyCollection();
                        m_MetaPropertyCollectionMap.Add(objectType, list);
                    }
                }
            }

            return list;
        }

        private IEnumerable<MetaProperty> GetPropertyEnumeration(Type objectType)
        {
            MetaPropertyCollection list;
            if (m_MetaPropertyCollectionMap.TryGetValue(objectType, out list))
            {
                foreach (var metaProperty in list)
                {
                    yield return metaProperty;
                }
            }
        }

        #endregion
    }
}